package net.xuele.learn.IO.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * Created by GaoQingming on 2019/4/11 0011.
 */
public class TimeClientHandler implements Runnable {

    private String host;
    private int port;
    private Selector selector;
    private SocketChannel socketChannel;
    private volatile boolean stop;

    public TimeClientHandler(String host, int port) {
        this.host = host;
        this.port = port;
        try {
            // 开启多路复用器
            selector = Selector.open();
            socketChannel = SocketChannel.open();
            socketChannel.configureBlocking(false);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    @Override
    public void run() {
        try {
            doConnect();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
        while (!stop) {
            try {
                selector.select(1000);
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                SelectionKey key;
                while (iterator.hasNext()) {
                    key = iterator.next();
                    iterator.remove();
                    try {
                        handleInput(key);
                    } catch (Exception e) {
                        if (key != null) {
                            key.cancel();
                            if (key.channel() != null) {
                                key.channel().close();
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.exit(1);
            }
        }
        if (selector != null) {
            try {
                selector.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 可能的事件是与服务端的连接以及读取服务端发送过来的消息！！！
    private void handleInput(SelectionKey key) throws IOException {
        if (key.isValid()) {
            SocketChannel channel = (SocketChannel) key.channel();
            //当前的事件是客户端连接服务端的操作
            if (key.isConnectable()) {
                if (channel.finishConnect()) {
                    // 如果连接已经完成后，就需要将对应的Channel注册读事件
                    channel.register(selector,SelectionKey.OP_READ);
                    // 向服务端发送消息
                    doWrite(channel);
                } else
                    // 连接失败，退出即可！！！
                    System.exit(1);
            }
            if (key.isReadable()) {
                //当前事件是读事件，需要将缓冲区里的数据复制到byte数组中，方便操作
                ByteBuffer allocate = ByteBuffer.allocate(1024);
                // channel.read方法底层会将ByteBuffer转换成DirectByteBuffer
                int read = channel.read(allocate);
                if (read > 0) {
                    allocate.flip();
                    byte[] bytes = new byte[allocate.remaining()];
                    allocate.get(bytes);
                    String s = new String(bytes, "UTF-8");
                    System.out.println("NOW IS"+s);
                    this.stop = true;
                } else if (read < 0){
                    key.cancel();
                    socketChannel.close();
                }
            }
        }
    }

    private void doConnect() throws IOException {
        // 如果直接连接成功，则注册到多路复用器上，发送请求信息，读应答等
        if (socketChannel.connect(new InetSocketAddress(host, port))) {
            socketChannel.register(selector, SelectionKey.OP_READ);
            // 连接上了之后，即TCP三次握手完成了，建立了物理链路
            doWrite(socketChannel);
        } else {
            // 未连接上，则需要注册连接事件
            socketChannel.register(selector, SelectionKey.OP_CONNECT);
        }

    }

    // 发送消息到服务端，通过channel来发送和读取！
    private void doWrite(SocketChannel socketChannel) throws IOException {
        byte[] bytes = "QUERY TIME ORDER".getBytes();
        ByteBuffer allocate = ByteBuffer.allocate(1024);
        allocate.put(bytes);
        allocate.flip();
        // socketChannel的write方法会将ByteBuffer转换成DirectByteBuffer。
        socketChannel.write(allocate);
        if (!allocate.hasRemaining()) {
            System.out.println("succeed");
        }
    }
}
